package com.hsq.reflection;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class ReflectionQuestion {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("D:\\git_turtle\\re.properties"));
        String classfullpath = properties.get("classfullpath").toString();
        String methodName = properties.get("method").toString();
        System.out.println("classfullpath=" + classfullpath);
        System.out.println("methodName=" + methodName);

        //加载类，返回Class类型的对象cls
        Class cls = Class.forName(classfullpath);
        //通过对象cls得到你加载的类com.hsq.reflection.Cat
        Object o = cls.newInstance();
        System.out.println("o的运行类型：" + o.getClass());
        //通过对象cls得到你加载的类com.hsq.reflection.Cat的methodName"hi"的对象
        //即：在反射中， 可以把方法视为对象(万物皆为对象)
        Method method1 = cls.getMethod(methodName);
        //通过method1调用的方法：即通过方法对象来实现调用方法
        method1.invoke(o); //传统方法   对象.方法()     方法.invoke(对象)
        //getField不能得到私有的成员
        Field ageField = cls.getField("age");
        System.out.println(ageField.get(o));
        Constructor constructor = cls.getConstructor();
        System.out.println(constructor);
        //传入的String.class就是String的Class对象
        Constructor constructor1 = cls.getConstructor(String.class);
        System.out.println(constructor1);
    }
}
